package com.bussiness.server.db.util;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

@SuppressWarnings("deprecation")
public abstract class AbstractDAS<T> {

	private Class<T> classEntity;

	static Configuration configuration = new AnnotationConfiguration()
			.configure();
	static SessionFactory factory = configuration.buildSessionFactory();

	static public Session getSession() {
		return factory.openSession();
	}

	protected String className() {
		return classEntity.getSimpleName();
	}

	@SuppressWarnings("unchecked")
	protected AbstractDAS() {
		ParameterizedType genericSuperclass = (ParameterizedType) getClass()
				.getGenericSuperclass();
		this.classEntity = (Class<T>) genericSuperclass
				.getActualTypeArguments()[0];

	}

	@SuppressWarnings("unchecked")
	protected List<T> findAll() {
		String hql = "FROM " + this.className();
		Query query = getSession().createQuery(hql);
		return query.list();
	}
	
	public boolean executeData(T entity, int type) {
		Session session = getSession();
		Transaction tran = session.beginTransaction();
		try{
			switch (type) {
			case 0:
				session.save(entity);
				break;
			case 1:
				session.update(entity);
				break;
			case 2:
				session.saveOrUpdate(entity);
				break;
			case 3:
				session.delete(entity);
				break;
			case 4:
				session.refresh(entity);
				break;
			}
			tran.commit();
			return true;
		}
		catch (Exception e) {
			tran.rollback();
			return false;
		}
		finally{
			session.close();
		}
	}

	 @SuppressWarnings("unchecked")
	public List<T> executeHqlPanagation(String hql, int firstResult, int maxResults) {
			Session session = getSession();
			Query query = session.createQuery(hql);
			if(firstResult >= 0 && maxResults > 0){
				query.setFirstResult(firstResult);
				query.setMaxResults(maxResults);
			}
			return query.list();
		}

    @SuppressWarnings("unchecked")
	public List<T> executeHql(String hql){
    	Query query = getSession().createQuery(hql);
    	return query.list();
    }

    
}
